﻿using IotClientApp.Server.Devices;
using IotClientApp.Server.Entity;
using IotClientApp.Shared;
using IotClientApp.Shared.Enums;
using Microsoft.EntityFrameworkCore;
using PluginInterface;

namespace IotClientApp.Server.Services
{
    public class DeviceConfigService : IDeviceConfigService
    {
        private readonly IotDBContext _iotDBContext;
        private readonly ILogger<IDeviceConfigService> _logger;
        public DeviceConfigService(IotDBContext iotDBContext, ILogger<IDeviceConfigService> logger)
        {
            _iotDBContext = iotDBContext;
            _logger = logger;
        }
        /// <summary>
        /// 获取所有设备
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResponse<DeviceConfigInfoModel>> GetDeviceConfigInfos(GetDeviceConfigInfoModel input)
        {
            var result = new PageResponse<DeviceConfigInfoModel> { Data = new List<DeviceConfigInfoModel> { } };
            try
            {
                var query = _iotDBContext.DeviceConfig.Where(t => t.DeviceId == input.DeviceId).AsQueryable();
                query = query.OrderBy(t => t.Name);
                result.PageCount = (int)Math.Floor(query.Count() / input.PageSize * 1.0);
                if (input.PageIndex > 0 && input.PageSize > 0)
                {
                    query = query.Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize);
                }
                var deviceConfigEntitys = await query.AsNoTracking().ToListAsync();
                foreach (var deviceConfigEntity in deviceConfigEntitys)
                {
                    result.Data.Add(new DeviceConfigInfoModel
                    {
                        Id = deviceConfigEntity.Id,
                        DeviceId = deviceConfigEntity.DeviceId,
                        Name = deviceConfigEntity.Name,
                        Desc = deviceConfigEntity.Desc,
                        Value = deviceConfigEntity.Value,
                        EnumInfo = deviceConfigEntity.EnumInfo
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"GetDeviceConfigInfos{ex.Message}");
            }
            return result;
        }
        /// <summary>
        /// 通信配置编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ApiResult<string>> SaveDeviceConfigInfo(DeviceConfigInfoModel input)
        {
            var result = new ApiResult<string> { };
            try
            {
                if (string.IsNullOrEmpty(input.DeviceId) || string.IsNullOrEmpty(input.Name))
                {
                    result.Code = ResultCode.BadRequest;
                    return result;
                }
                var isExit = _iotDBContext.DeviceConfig.Any(t => t.Id != input.Id && t.DeviceId == input.DeviceId && t.Name == input.Name);
                if (isExit)
                {
                    result.Code = ResultCode.Exist;
                    return result;
                }

                Entity.DeviceConfig? deviceConfig;
                if (input.Id > 0)
                {
                    deviceConfig = _iotDBContext.DeviceConfig.FirstOrDefault(t => t.Id == input.Id && t.DeviceId == input.DeviceId);
                    if (deviceConfig == null)
                    {
                        result.Code = ResultCode.NotExist;
                        return result;
                    }
                    _iotDBContext.Attach(deviceConfig);
                    _iotDBContext.Entry(deviceConfig).Property(p => p.Name).IsModified = true;
                    _iotDBContext.Entry(deviceConfig).Property(p => p.Value).IsModified = true;
                    _iotDBContext.Entry(deviceConfig).Property(p => p.Desc).IsModified = true;
                    _iotDBContext.Entry(deviceConfig).Property(p => p.EnumInfo).IsModified = true;
                }
                else
                {
                    deviceConfig = new Entity.DeviceConfig { DeviceId = input.DeviceId };
                    _iotDBContext.DeviceConfig.Add(deviceConfig);
                }
                deviceConfig.Name = input.Name;
                deviceConfig.Value = input.Value;
                deviceConfig.Desc=input.Desc;
                deviceConfig.EnumInfo = input.EnumInfo;
                await _iotDBContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"GetDeviceConfigInfos{ex.Message}");
            }
            return result;
        }
    }
}